// src/main/java/com/example/cmd2/service/impl/UserServiceImpl.java
package top.csh215.cmd2.service.serviceImpl;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import top.csh215.cmd2.entity.Permission;
import org.springframework.stereotype.Service;
import top.csh215.cmd2.entity.Role;
import top.csh215.cmd2.entity.User;
import top.csh215.cmd2.mapper.UserMapper;
import top.csh215.cmd2.service.UserService;
import top.csh215.cmd2.utils.EncryptUtils;

import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Resource
    private UserMapper userMapper;


    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public User getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public boolean login(String username, String password) {
        User user = getByUsername(username);
        if (user == null) {
            return false;
        }

        // 密码加密验证逻辑
        try {
            String md5 = EncryptUtils.md5(password);
            return user.getPassword().equals(md5);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 根据用户ID获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public User getUserInfoById(Integer userId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId)
               .eq("status", "0") // 确保用户未被禁用
               .eq("is_delete", "0"); // 确保用户未被逻辑删除

        return userMapper.selectOne(wrapper);
    }

    /**
     * 获取用户角色列表
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<Role> getUserRoles(Integer userId) {
        return userMapper.selectRolesByUserId(Long.valueOf(userId));
    }

    /**
     * 获取用户权限列表
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public List<Permission> getUserPermissions(Integer userId) {
        return userMapper.selectPermissionsByUserId(Long.valueOf(userId));
    }

}
